package com.dhms.uikit

import android.text.InputFilter
import android.text.Spanned
import java.util.regex.Pattern

/**
 * A decimal digits input filter for EditText.
 */
class DecimalDigitsInputFilter(
    digitsBeforeDecimal: Int,
    digitsAfterDecimal: Int
) : InputFilter {

    private val pattern: Pattern =
        Pattern.compile("-*(([1-9][0-9]{0," + (digitsBeforeDecimal - 1) + "})?||[0])((\\.[0-9]{0," + digitsAfterDecimal + "})?)||(\\.)?")

    override fun filter(
        source: CharSequence?,
        start: Int,
        end: Int,
        dest: Spanned?,
        dstart: Int,
        dend: Int
    ): CharSequence? {
        val formattedSource = source?.subSequence(start, end).toString()
        val destPrefix = dest?.subSequence(0, dstart).toString()
        val destSuffix = dest?.subSequence(dend, dest.length).toString()

        val result = destPrefix + formattedSource + destSuffix
        val matcher = pattern.matcher(result)
        if (matcher.matches()) {
            return null
        }

        return ""
    }
}